package day05.homework.standard;

import java.util.Arrays;
import java.util.Random;

/*
 数组小代码练习：声明、初始化、访问、遍历、复制
 */
public class ArrayTest2 {
    public static void main(String[] args) {
        // 声明,初始化:定义至少两个数组，设计包含一些元素;定义至少三个数组，演示三种元素初始化方式
        int[] arr1 = new int[5];// 0,0,0,0,0
        int[] arr2 = {1, 3, 5, 7, 9};
        int[] arr3 = new int[]{2, 4, 6, 8, 9};
        int[] arr4;
        int[] arr5;
        // arr4 = {2,4,6,8}// 这样初始化是行不行的
        arr4 = new int[5];
        arr5 = new int[]{1, 2, 4, 5, 6};

        // 定义数组，输出数组的长度
        System.out.println(arr3.length);// 5

        // 定义数组并分别给每个元素赋值，输出最后一个元素的值,常见的异常----数组下标越界
        int[] arr6 = new int[3];
        arr6[0] = 100;
        arr6[1] = 200;
        arr6[2] = 500;
        // arr6[3] = 300;// 异常ArrayIndexOutOfBoundsException，数组下标越界
        System.out.println("最后一个元素的值:" + arr6[arr6.length - 1]);

        // 遍历
        // 定义数组，包含10个元素，遍历数组，给每个元素赋值为0到99之间的随机数，输出每个元素的值
        int[] arr7 = new int[10];
        System.out.println("0到99之间的随机数:");
        for (int i = 0; i < arr7.length; i++) {
            Random rand = new Random();
            arr7[i] = rand.nextInt(99);
            System.out.println(arr7[i]);
        }

        // 复制   1.扩容
        int[] arr8 = {2, 8, 4, 7, 1};
        arr8 = Arrays.copyOf(arr8, 9);
        System.out.println("扩容后：");
        for (int i = 0; i < arr8.length; i++) {
            System.out.println(arr8[i]);
        }
        // 复制
        int[] arr9 = {1, 2, 3, 4, 5};
        int[] arr10 = {9, 8, 7};
        System.arraycopy(arr9, 1, arr10, 1, 2);
        System.out.println("复制后：");
        for (int i = 0; i < arr10.length; i++) {
            System.out.println(arr10[i]);
        }
        int[] arr11 = {1, 2, 3, 4, 5};
        int[] arr12 = new int[10];

        System.arraycopy(arr11, 2, arr12, 2, 2);
        System.out.println("复制后：");
        for (int i = 0; i < arr12.length; i++) {
            System.out.println(arr12[i]);
        }
    }
}
